<?php
namespace app\module\controllers;

use app\models\AddressRecorder;
use app\models\AmountRecorder;
use app\models\CouponRecorder;
use app\models\CouponuserRecorder;
use app\models\DiscountRecorder;
use app\models\GoodsRecorder;
use app\models\KuaidiRecorder;
use app\models\MemberRecorder;
use app\models\NewRecorder;
use app\models\PurchaseRecorder;
use app\models\RateRecorder;
use app\models\RateuseRecorder;
use app\models\SetRecorder;
use function GuzzleHttp\Psr7\str;

class ContentController extends BaseController{

    //获取商品内容
    //参数：$id-商品id
    public function actionOne(){
        $id = \Yii::$app->request->post('id');
        $address_id = intval(\Yii::$app->request->post('address'));
        $model = GoodsRecorder::find()->select(['id','goods_name','thumb_pic','goods_small_name','goods_attr','pics','content','hits',
            'goods_num','goods_weight','goods_unit','sell_num','goods_price','goods_hd_price','specs','specs_attr','specs_value',
            'new_id','discount_id','purchase_id','amount_id','cate_id'])->where('id=:id',[':id' => $id])->asArray()->one();
        if(empty($model)){
            $result = ['result'=>0,'data'=>'没有相关商品，可能已经下架,请查看其它商品'];
            return json_encode($result);
        }
        $hits_model = GoodsRecorder::find()->where('id='.$model['id'])->one();
        $hits_model->hits++;
        $hits_model->save(false);
        $model['pics'] = json_decode($model['pics'],true);
        foreach($model['pics'] as $k=>$v){
            $model['pics'][$k] = \Yii::$app->params['base_url'].$v;
        }
        $model['thumb_pic'] = \Yii::$app->params['base_url'].$model['thumb_pic'];
        $model['goods_attr'] = empty($model['goods_attr'])?[]:json_decode($model['goods_attr'],true);
        $model['specs'] = empty($model['specs'])?[]:json_decode($model['specs'],true);
        $model['specs_attr'] = empty($model['specs_attr'])?[]:json_decode($model['specs_attr'],true);
        $model['specs_value'] = empty($model['specs_value'])?[]:json_decode($model['specs_value'],true);
        $model['percent'] = $this->get_percent($model['goods_num'],$model['sell_num']);
        $model['content'] = str_replace("<img",'<img style="width:100%;height:auto;padding:0;margin:0;"',$model['content']);

        //配送时间
        $model['send_time'] = $this->get_send_time($address_id);
        $hd_arr=[];
        $arr=[];
        if($model['new_id']){
            $new = NewRecorder::find()->select(['id','title','g_limit'])->where('id='.$model['new_id'])->andWhere('status=0')->one();
            $arr['id'] = $new->id;
            $arr['title'] = $new->title;
            $arr['limit'] = $new->g_limit;
            $hd_arr[]=$new->title;
        }
        $model['new_info'] = $arr;

        $arr=[];
        if($model['discount_id']){
            $dis = DiscountRecorder::find()->where('id='.$model['discount_id'])->andWhere('status=0')->one();
            $arr['id'] = $dis->id;
            $arr['title'] = $dis->title;
            $arr['content'] = empty($dis->content)?[]:json_decode($dis->content,true);
            $hd_arr[]=$dis->title;
        }
        $model['discount_info'] = $arr;

        $arr=[];
        if($model['purchase_id']){

            $pur = PurchaseRecorder::find()->where('id='.$model['purchase_id'])->andWhere('status=0')->one();
            $arr['id'] = $pur->id;
            $arr['title'] = $pur->title;
            $arr['begintime'] = date('Y-m-d H:i:s',$pur->begintime);
            $arr['endtime'] = date('Y-m-d H:i:s',$pur->endtime);
            $arr['limit'] = $pur->g_limit;
            $time = $pur->endtime-time();
            $arr['is_end']=0;
            if($time<=0){
                $arr['is_end'] = 1;//结束
                $time=0;
            }else{
//                $time = intval($time/60);
            }
            $arr['time'] = $time*1000;//毫秒
            $hd_arr[]=$pur->title;
        }
        $model['purchase_info'] = $arr;


        if($model['amount_id']){
            $arr=[];
            $amount= AmountRecorder::find()->where('id='.$model['amount_id'])->andWhere('status=0')->one();
            if($amount){
                $arr['id'] = $amount->id;
                $arr['count'] = $amount->count;
                $arr['reduce'] = $amount->reduce;
                $hd_arr[]="满".$amount->count."元减".$amount->reduce."元";
            }
            $model['amount_info']=$arr;
        }

        $model['hd_name'] = (count($hd_arr)<=0)?"":$hd_arr[array_rand($hd_arr,1)];

        //购物
        $web_info = SetRecorder::find()->where('set_type=1')->asArray()->one();
        $content = json_decode($web_info['content'],true);
        $model['buy_info'] = $content['buy_info'];


        $result = ['result'=>1,'data'=>$model];
        return json_encode($result,JSON_NUMERIC_CHECK);

    }



    //获取商品规格
    //参数：$id-商品id
    public function actionAttr(){
        $id = \Yii::$app->request->post('id');
        $model = GoodsRecorder::find()->select(['id','goods_name','thumb_pic','goods_small_name','goods_attr',
            'goods_num','goods_weight','goods_unit','sell_num','goods_price','goods_hd_price','specs','specs_attr','specs_value',
            'cate_id'])->where('id=:id',[':id' => $id])->asArray()->one();
        if(empty($model)){
            $result = ['result'=>0,'data'=>'没有相关商品，可能已经下架,请查看其它商品'];
            return json_encode($result);
        }
        $model['thumb_pic'] = \Yii::$app->params['base_url'].$model['thumb_pic'];
        $model['goods_attr'] = empty($model['goods_attr'])?[]:json_decode($model['goods_attr'],true);
        $model['specs'] = empty($model['specs'])?[]:json_decode($model['specs'],true);
        $model['specs_attr'] = empty($model['specs_attr'])?[]:json_decode($model['specs_attr'],true);
        $model['specs_value'] = empty($model['specs_value'])?[]:json_decode($model['specs_value'],true);
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result);
    }


    public function actionAttrgoods(){
        $attr = \Yii::$app->request->post('attr');
        $id = \Yii::$app->request->post('id');
        if(!is_array($attr)){
            $result = ['result'=>0,'data'=>'参数发生错误，请重新操作'];
            return json_encode($result);
        }
        $model = GoodsRecorder::find()->select(['specs','specs_attr','specs_value','new_id','discount_id','purchase_id'])->where("id=:id",[':id' => $id])->one();
        if(empty($model)){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $specs = empty($model->specs)?[]:json_decode($model->specs,true);
        $specs_attr = empty($model->specs_attr)?[]:json_decode($model->specs_attr,true);
        $specs_value = empty($model->specs_value)?[]:json_decode($model->specs_value,true);
        foreach($specs_value as $k=>$v){
            $specs_value[$k]['pic'] = \Yii::$app->params['base_url'].$v['pic'];
        }
        $index=-1;
        $goods=[];
        $return=[];
        $result = ['result'=>2];
        foreach($specs_attr as $k=>$v){
            if(implode(",",$attr)==implode(",",$v)){
                $index=$k;
            }
        }
        if($index > -1){
            $goods = $specs_value[$index];
        }
        if(count($goods)>0){
            $return['goods_price'] = $goods['price'];
            $return['goods_num'] = $goods['num'];
            $return['thumb_pic'] = $goods['pic'];
            $return['info'] = ($goods['num']>0)?"":"商品已经出售完了";
            $return['is_num'] = ($goods['num']>0)?1:0;
//            if($model->new_id||$model->discount_id||$model->purchase_id){
//                $return['goods_price'] = ($goods['hd_num']>0)?$goods['hd_price']:$goods['price'];
//                $return['old_price'] = $goods['price'];
//                $return['goods_num'] = ($goods['hd_num']>0)?$goods['hd_num']:$goods['num'];
//                $return['thumb_pic'] = $goods['pic'];
//                $return['info'] = ($goods['hd_num']>0)?"":"活动商品已经出售完了";
//                $return['is_num'] = ($goods['num']>0)?1:0;
//            }else{
//                $return['goods_price'] = $goods['price'];
//                $return['old_price'] = $goods['price'];
//                $return['goods_num'] = $goods['num'];
//                $return['thumb_pic'] = $goods['pic'];
//                $return['info'] = ($goods['num']>0)?"":"商品已经出售完了";
//                $return['is_num'] = ($goods['num']>0)?1:0;
//            }
            $result = ['result'=>1,'data'=>$return,"attr_id"=>$index];
        }

        return json_encode($result);
    }



    public function actionYhq(){
        $list = CouponRecorder::find()->where('status=0')->orderBy('addtime DESC')->asArray()->all();
        foreach($list as $k=>$v){
            $list[$k]['name'] = "满".$v['count']."元减".$v['reduce']."元";
        }
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result,JSON_NUMERIC_CHECK);
    }


    public function actionGetyhq(){
        //判断是否登录
        if(!$this->check_login()){
            $result = ['result'=>'login_error','data'=>'请先登录'];
            return json_encode($result);
        }
        $id = \Yii::$app->request->post('id');

        $coupon = CouponRecorder::find()->where('id=:id',[':id' => $id])->one();
        if(empty($coupon)){
            $result = ['result'=>0,'data'=>'不存在优惠券，请重新操作'];
            return json_encode($result);
        }
        if($coupon->num<=0){
            $result = ['result'=>0,'data'=>'该优惠券已经没有了'];
            return json_encode($result);
        }
        $count = CouponuserRecorder::find()->where('coupon_id=:id',[':id' => $id])->andWhere('user_id='.$this->user->id)->count();
        if($count>=$coupon->p_limit){
            $result = ['result'=>0,'data'=>'已经领取过该优惠券了'];
            return json_encode($result);
        }
        $model = new CouponuserRecorder();
        $model->addtime = time();
        $model->coupon_id = intval($id);
        $model->user_id = $this->user->id;
        $model->save(false);
        $coupon->num =($coupon->num-1)<0?0:$coupon->num-1;
        $coupon->save(false);
        $result = ['result'=>1,'data'=>'领取成功'];
        return json_encode($result);
    }


    public function actionHits(){
        $id = \Yii::$app->request->post('id');
        $model = GoodsRecorder::find()->where('id=:id',[':id' => $id])->one();
        if($model){
            $model->hits++;
            $model->save(false);
        }
    }

    //指定评价数量
    //参数：{param:{id:0,num:2}}  id-商品id,num-输出数量
    public function actionRatenumlist(){
        $post = \Yii::$app->request->post('param');
        $id = $post['id'];
        $num = intval($post['num']);
        if($num<=0){
            return [];
        }
        $list = RateRecorder::find()->select(['id','goods_id','user_id','pics','content','use_hits','addtime','rate','attr','hf_content','is_name']);
        $list = $list->where('goods_id=:id',[':id' => $id])->limit($num)->orderBy('addtime DESC')->asArray()->all();
        foreach($list as $k=>$v){
            //获取会员
            $user = MemberRecorder::find()->where('id='.$v['user_id'])->one();
            if($user){
                $arr['user_pic'] = empty($user->user_pic)?"":\Yii::$app->params['base_url'].$user->user_pic;
                $arr['user_name'] = (!empty($user->user_name))?$user->user_name:"微信用户";
            }else{
                $arr['user_pic'] = "";
                $arr['user_name'] = "微信用户";
            }
            if($v['is_name']){
                $arr['user_pic'] = "";
                $arr['user_name'] = "微信用户";
            }
            $list[$k]['user'] = $arr;
            $list[$k]['user_id']=0;
            $v['pics'] = json_decode($v['pics'],true);
            $pic_arr = [];
            foreach($v['pics'] as $pv){
                $pic_arr[] = str_replace("../",\Yii::$app->params['base_url'],$pv);
            }
            $list[$k]['thumb_pic'] = $pic_arr[0];
            $list[$k]['pics'] = $pic_arr;
            $list[$k]['addtime'] = date('Y-m-d');
            $list[$k]['attr'] = empty($v['attr'])?'':json_decode($v['attr'],true);
            $use_hits = RateuseRecorder::find()->where('rate_id='.$v['id'])->count();
            $use_hits = ($use_hits>=100)?"99+":$use_hits;
            $list[$k]['use_hits'] = $use_hits;
        }
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result);
    }

    public function actionAddrateuse(){
        //判断是否登录
        if(!$this->check_login()){
            $result = ['result'=>'login_error','data'=>'请先登录'];
            return json_encode($result);
        }
        $id = \Yii::$app->request->post('id');
        $is = RateuseRecorder::find()->where('rate_id=:id',[':id' => $id])->andWhere('user_id='.$this->user->id)->count();
        if($is){
            $result = ['result'=>0,'data'=>'已经操作过了'];
            return json_encode($result);
        }
        $model = new RateuseRecorder();
        $model->rate_id = intval($id);
        $model->user_id = $this->user->id;
        $model->save(false);
        $result = ['result'=>1,'data'=>'操作成功'];
        return json_encode($result);
    }



}